<?php
/**
 * String.php
 *
 * 字符处理类
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://momoger.com/license
 *
 * @category	App
 * @package 	App_Util
 * @author 		Guya
 * @version    	1.0
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */

/**
 * 字符处理类
 *
 * @category	App
 * @package 	App_Util
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */
class App_Util_String {

	/**
	 * 中英文字符混合截取
	 *
	 * @param string $str 要进行截取的字符串
	 * @param int $start 开始截取位置
	 * @param int $len 截取长度
	 * @param string $more 超过部分默认显示模式
	 * @param string $charset 字符编码
	 * @return string
	 */
	public static function substr($str = '', $start = 0, $len = 10000, $more = '...', $charset = 'UTF-8') {
		if ($len) {
			$_start = $start;
			$_len = $len;
		}else {
			$_start = 0;
			$_len = $start;
		}



		if(function_exists('mb_substr')) {
			$str_len = mb_strlen($str, $charset);
			if ($str_len <= $_len) {
				return $str;
			} else {
				$more_len = mb_strlen($more);
				if (($str_len > ($_start + $_len)) && $_len > $more_len) {
					$_len = $_len - $more_len;
				}
			}
		} else {
			$str_len = strlen($str);
			if ($str_len <= $_len) {
				return $str;
			} else {
				$more_len = strlen($more);
				if (($str_len > ($_start + $_len)) && $_len > $more_len) {
					$_len = $_len - $more_len;
				}
			}
		}

		if(function_exists("mb_substr")) {
			return mb_substr($str, $_start, $_len, strtoupper($charset)) . $more;
		}

		$re['UTF-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['GB2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['GBK'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['BIG5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[strtoupper($charset)], $str, $match);
		$slice = join('', array_slice($match[0], $_start, $_len));
		return $slice . $more;
	}

	/**
	 * 去除一段字符串中不全的 <img/> 标记
	 *
	 * @param reference $str 字符串地址
	 * @return void
	 */
	public static function stripHalfwayImgTag(& $str) {
		$lastImgStr = strrchr($str,'<');
		if($lastImgStr) {
			if(strpos($lastImgStr,'>')) {
				$str = substr($str, 0, strripos($str, '<img'));
			}
		}
	}
}